package com.example.m_kartupay;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;




import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.net.ParseException;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.ListAdapter;
import android.widget.SimpleAdapter;
import android.widget.TextView;
import android.widget.Toast;

import com.example.m_kartupay.library.DatabaseHandler;
import com.example.m_kartupay.library.InquiryDatabaseHandler;
import com.example.m_kartupay.library.StrictWrapper;
import com.example.m_kartupay.library.UserFunctions;
import com.example.m_kartupay.MainActivity;
import com.example.m_kartupay.MainMenuActivity;
import com.example.m_kartupay.R;


public class LoginActivity extends Activity {
	
	private ProgressDialog pDialog; 
	Button btnLogin;
	Button btnLinkToRegister;
	Button btnLinkToForget;
	EditText inputEmail;
	EditText inputPassword;
	
	TextView loginErrorMsg;
	Integer logNumber;
	LinearLayout  lyCollap; 
	// JSON Response node names
	
	private static String KEY_SUCCESS = "success";
	private static String KEY_ERROR = "error";
	private static String KEY_ERROR_MSG = "error_msg";
	private static String KEY_UID = "user_id";
	private static String KEY_NAME = "name";
	private static String KEY_EMAIL = "email";
	private static String KEY_CREATED_AT = "created_at";
	UserFunctions userFunction = null; 
	JSONObject json = null;
	JSONObject json_user = null;
	
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);		setContentView(R.layout.login);
		StrictWrapper.init();
			
		inputEmail = (EditText) findViewById(R.id.etloginEmail);
		inputPassword = (EditText) findViewById(R.id.etLoginPassword);
		btnLogin = (Button) findViewById(R.id.btnLogin);
		btnLinkToRegister = (Button) findViewById(R.id.btnLoginRegister);
		btnLinkToForget = (Button) findViewById(R.id.btnLinkToForgotPassword); 
		
		loginErrorMsg = (TextView) findViewById(R.id.ttLoginError);
		LinearLayout  lyCollap = (LinearLayout)findViewById(R.id.layCollap);			
		// Login button Click Event
		btnLogin.setOnClickListener(new View.OnClickListener() {

			public void onClick(View view) {
								
				new LoginLogOut().execute();
               
					
				// check for login response			}
		});
		btnLinkToRegister.setOnClickListener(new View.OnClickListener() {

			public void onClick(View view) {
				Intent i = new Intent(getApplicationContext(),
						RegisterActivity.class);
				startActivity(i);
				finish();
			}
		});

		btnLinkToForget.setOnClickListener(new View.OnClickListener() {

			public void onClick(View view) {
				Intent i = new Intent(getApplicationContext(),
						ForgotPasswordActivity.class);
				startActivity(i);
				//finish();
			}
		});

	}
// class asyncronus
	 class LoginLogOut extends AsyncTask<String, Void, Boolean> {

			/**
			 * Before starting background thread Show Progress Dialog
			 * */
			@Override
			protected void onPreExecute() {
				super.onPreExecute();
				pDialog = new ProgressDialog(LoginActivity.this);
				pDialog.setMessage("Please wait ...");
				pDialog.setIndeterminate(false);
				pDialog.setCancelable(true);
				pDialog.show();
			}

			/**
			 * Creating product
			 * */
			protected Boolean doInBackground(String... args) {				
				String channel_id = "123456789";
				String email = inputEmail.getText().toString();
				String password = inputPassword.getText().toString();	
				
				// debug tanpa koneksi login
				/*
				Intent in = new Intent(LoginActivity.this, MainMenuActivity.class);
				in.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
			    //in.putExtra("kirim", "Hallo Saya dari FirstActivity");
			    startActivity(in);
				*/
				
			    userFunction = new UserFunctions();
			    json = userFunction.loginUser(channel_id,email, password);
			    Log.d("JSON DATA", json.toString()); 
				  String res;
				try {
					res = json.getString("responseCode");
					Log.d("Response Code", res.toString());
					 if(Integer.parseInt(res) ==00)
					  {
						 Log.d("Panggil Activiy", "MainMenu Activity");
						  DatabaseHandler db = new DatabaseHandler(getApplicationContext());
						  
						  
						  json_user = json.getJSONObject("data");
						 
						  db.addUser(json_user.getString("user_id"),json_user.getString("name"), json_user.getString("email"), password,json_user.getString("gender"), "18-11-2014");
						  
						  Intent main = new Intent(LoginActivity.this, MainMenuActivity.class);
						  main.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
						    //in.putExtra("kirim", "Hallo Saya dari FirstActivity");
						    startActivity(main);
						    finish();
						   
						 return true;
						 
					  }
					 
					 
					} catch (ParseException e1) {
						e1.printStackTrace();
					
					} catch (JSONException e) {
						e.printStackTrace();
					}
				 
					return false;
				  
			   
			}
					
		

			/**
			 * After completing background task Dismiss the progress dialog
			 * **/
			
			protected void onPostExecute(Boolean result) {			
				pDialog.cancel();
			
				if(result == false)
				{		
					
					 		
					//Toast.makeText(getApplicationContext(), "Unable to fetch data from server", Toast.LENGTH_LONG).show();
					 runOnUiThread(new Runnable() {
							public void run() {								
																
							 loginErrorMsg.setText("Login Failed");
											
							}
							
						});
					 
				}
				
 
				
				
							
			}
			

		}
	

}
